// @ts-nocheck
import { reactive } from '@/uni_modules/lime-shared/vue'
import { isBrowser } from '@/uni_modules/lime-shared/isBrowser'

const { platform, pixelRatio } = uni.getSystemInfoSync()
const isPc = /window|mac/.test(platform)
export const canIUseOffscreenCanvas = uni.canIUse('createOffscreenCanvas') && Boolean(uni.createOffscreenCanvas) && !isPc || isBrowser

export interface Context extends UniNamespace.CanvasContext {
	getImageData: (x:number, y:number, width:number, height: number) => void
}
export function useCanvas(canvasId: string, context: any) {
	if(canIUseOffscreenCanvas) return
	// #ifdef MP || VUE2
	if (context.proxy) context = context.proxy
	// #endif
	const ctx = uni.createCanvasContext(canvasId, context) as Context;
	const {drawImage} = ctx
	if(!ctx.drawImageClone) {
		ctx.drawImageClone = drawImage
		ctx.drawImage = ({path},...args: number[]) => {
			ctx.drawImageClone(path, ...args)
		};
	}
	ctx.getImageData = (x:number, y:number, width:number, height: number) => {
		return new Promise((resolve, reject) => {
			uni.canvasGetImageData({
				canvasId,
				x,
				y,
				width,
				height,
				success(res) {
					resolve(res)
				},
				fail(error) {
					reject(error)
				}
			}, context)
		})
	}
	const canvas = reactive({
		width: 0,
		height: 0,
		getContext: (type: string = '2d') => {
			if(type == '2d') {
				return ctx
			}
		},
		toDataURL: (type: string, quality: number) => {
			return new Promise((resolve, reject) => {
				const options = {
					canvasId,
					quality,
					fileType: type.replace('image/','').replace('jpeg', 'jpg'),
					// pc端导出的尺寸与画板大小不一致
					destHeight: canvas.height / (isPc ?pixelRatio:1),
					destWidth: canvas.width / (isPc ? pixelRatio:1),
					success(res) {
						resolve(res.tempFilePath)
					},
					fail: reject
				}
				uni.canvasToTempFilePath(options, context)
			})
		}
	})
	
	return canvas
}